package com.jf.apply_car.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jf.apply_car.bean.Foreign;
import com.jf.apply_car.bean.Userinfo;
import com.jf.apply_car.mapper.ForeignMapper;
import com.jf.apply_car.mapper.UserinfoMapper;
import com.jf.apply_car.service.ForeignService;
import com.jf.apply_car.util.BusinessException;
import com.jf.apply_car.util.MyConstants;
import com.jf.apply_car.util.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ForeignServiceImpl implements ForeignService {
    @Autowired
    private ForeignMapper foreignMapper;
    @Autowired
    private UserinfoMapper userinfoMapper;

    public ResultJson getPage(int page, int limit, Foreign foreign) {
        PageHelper.startPage(page, limit);
        List<Foreign> list = foreignMapper.getAll(foreign);
        PageInfo<Foreign> pageInfo = new PageInfo<Foreign>(list);
        return ResultJson.page(pageInfo.getTotal(), list);
    }

    public void delete(int[] ids, int type) {
        if (type == MyConstants.DEPARTMENT_TYPE) {
            Userinfo userinfo = new Userinfo();
            for (int dId : ids) {
                userinfo.setDepartmentId(dId);
                List<Userinfo> userinfoList = userinfoMapper.getAll(userinfo);
                if (!userinfoList.isEmpty()) {
                    throw new BusinessException("编号[" + dId + "]存在关联用户，禁止删除");
                }
            }
        }
        // todo 品牌和分类的关联删除
        foreignMapper.deleteBatch(ids);
    }

    public void saveOrUpdate(Foreign foreign) {
        if (foreign.getId() == null) {
            foreignMapper.insertSelective(foreign);
        } else {
            foreignMapper.updateByPrimaryKeySelective(foreign);
        }
    }

    public ResultJson getById(int id) {
        return ResultJson.success(foreignMapper.selectByPrimaryKey(id));
    }

    public ResultJson getSelect(int type) {
        Foreign foreign = new Foreign();
        foreign.setType(type);
        return ResultJson.success(foreignMapper.getAll(foreign));
    }
}
